//
//  CustodyViewController.m
//  TourDeGarde
//
//  Created by Guillaume SOURDRILLE on 05/05/12.
//  Copyright (c) 2012 Astek. All rights reserved.
//

#import "CustodyViewController.h"
#import "Custody.h"
#import "DateUtils.h"

@implementation CustodyViewController
@synthesize nameButton;
@synthesize beginDateButton;
@synthesize endDateButton;
@synthesize isActiveButton;
@synthesize backButton;
@synthesize saveButton;
@synthesize custody;
@synthesize actionSheetDateFin;
@synthesize actionSheetDateDebut;
@synthesize datePickerDateFin;
@synthesize nameTextField;
@synthesize deleteButton;
@synthesize beginDateValue;
@synthesize endDateValue;
@synthesize isActiveValue;
@synthesize datePickerDateDebut;
@synthesize dateUtils;
@synthesize titleValue;
@synthesize messageUtils;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        custody = [[Custody alloc]initCustody];
        isNew = YES;
        }
    return self;
}

- (id)initWithCustody:(Custody *)param
{
    self = [super init];
    if (self) {
        custody = param;
        isNew = NO;
    }
    return self;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //To have a background
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    UITableView *tv = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:tv];
    [self.view sendSubviewToBack:tv];

    [self initParameters];
    [self updateParameters];
}

- (void)viewDidUnload
{
    [self setNameButton:nil];
    [self setBeginDateButton:nil];
    [self setEndDateButton:nil];
    [self setIsActiveButton:nil];
    [self setBackButton:nil];
    [self setSaveButton:nil];
    custody = nil;
    [self setBeginDateValue:nil];
    [self setEndDateValue:nil];
    [self setIsActiveValue:nil];
    [self setTitleValue:nil];
    [self setNameTextField:nil];
    [self setDeleteButton:nil];
    [super viewDidUnload];
    dateUtils = nil;
    messageUtils = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [nameTextField resignFirstResponder];
    return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)initParameters{
    
   
    dateUtils = [[DateUtils alloc]initWithHours];
    messageUtils = [[MessageUtils alloc]init];
    
    nameTextField.delegate = self;
    nameTextField.placeholder = NSLocalizedString(@"Menu.name.placeholder", @"");
    
    [nameButton setTitle: NSLocalizedString(@"Menu.button.name", @"") forState:UIControlStateNormal];
    nameButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [beginDateButton setTitle: NSLocalizedString(@"Menu.button.date.debut", @"") forState:UIControlStateNormal];
    beginDateButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [endDateButton setTitle: NSLocalizedString(@"Menu.button.date.fin", @"") forState:UIControlStateNormal];
    endDateButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [isActiveButton setTitle: NSLocalizedString(@"Menu.button.active", @"") forState:UIControlStateNormal];
    isActiveButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    saveButton.title = NSLocalizedString(@"Commun.button.ok", @"");
    backButton.title = NSLocalizedString(@"Commun.button.back", @"");
       
    NSString *beginDateSettings =   [dateUtils getStringFromDate:[custody beginDate]];
    if (beginDateSettings == nil || [beginDateSettings isEqualToString:@""]){
        [beginDateValue setText:NSLocalizedString(@"Menu.label.non.defini", @"")];
    }else{
        [beginDateValue setText:beginDateSettings];
    }
    
    NSString *endDateSettings = [dateUtils getStringFromDate:[custody endDate]];
    if (endDateSettings == nil || [endDateSettings isEqualToString:@""]){
        [endDateValue setText:NSLocalizedString(@"Menu.label.non.defini", @"")];
    }else{
        [endDateValue setText:endDateSettings];
    }
    
     
    BOOL periodeActiveSettings = [custody isActive]; 
    if (periodeActiveSettings){
        [isActiveValue setText:NSLocalizedString(@"Yes", @"")];
    }else{
        [isActiveValue setText:NSLocalizedString(@"Non", @"")];    
    }
    
    NSString *titleSettings = [custody name]; 
    if (titleSettings == nil || [titleSettings isEqualToString:@""]){
        [nameTextField setText:@""];
        [titleValue setText:NSLocalizedString(@"Menu.label.new", @"")];
    }else{
        [nameTextField setText:titleSettings];
        [titleValue setText:titleSettings];
    }
    
    [self.deleteButton setBackgroundImage:[[UIImage imageNamed:@"delete_button.png"]
                                           stretchableImageWithLeftCapWidth:8.0f
                                           topCapHeight:0.0f]
                                 forState:UIControlStateNormal];
    
    [self.deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.deleteButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    self.deleteButton.titleLabel.shadowColor = [UIColor lightGrayColor];
    self.deleteButton.titleLabel.shadowOffset = CGSizeMake(0, -1);
    [self.deleteButton setTitle: NSLocalizedString(@"Commun.button.delete", @"") forState:UIControlStateNormal];
    
}

-(void)actionSheet:(UIActionSheet *)action clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (action == actionSheetDateDebut){
        if (buttonIndex == 0) {
            NSDate *pickerDate = [datePickerDateDebut  date];      
            NSString *selectionString = [dateUtils getStringFromDate:pickerDate];
            [custody setBeginDate:pickerDate];
            [beginDateValue setText:selectionString];
        }       
    }else if(action == actionSheetDateFin){
        if (buttonIndex == 0) {
            NSDate *pickerDate = [datePickerDateFin  date];      
            NSString *selectionString = [dateUtils getStringFromDate:pickerDate];
            [custody setEndDate:pickerDate];
            [endDateValue setText:selectionString];
        }
    }
    
}


-(IBAction) setPeriodeActive {
    
        if (![custody isActive]){
            [custody setActive:YES];
            [isActiveValue setText:NSLocalizedString(@"Yes", @"")];
        
        }else{
            [custody setActive:NO];
            [isActiveValue setText:NSLocalizedString(@"No", @"")];
    
        }
}

- (IBAction)setDateDebut{
    
    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n" ; 
    actionSheetDateDebut = [[UIActionSheet alloc]  
                            initWithTitle:[NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"dateDebut", @"")] 
                            delegate:self cancelButtonTitle:NSLocalizedString(@"Commun.button.cancel", @"") destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Commun.button.select", @""), nil]; 
    [actionSheetDateDebut showInView:self.view]; 
    datePickerDateDebut = [[UIDatePicker alloc] init]; 
    datePickerDateDebut.datePickerMode = UIDatePickerModeDateAndTime; 
    [actionSheetDateDebut addSubview:datePickerDateDebut]; 
    
    if ([custody beginDate] != nil){
        datePickerDateDebut.date = [custody beginDate];
    }else{
        datePickerDateDebut.date=[NSDate date];
    }
    
    
    
}

- (IBAction)setDateFin {
    
    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n" ; 
    actionSheetDateFin = [[UIActionSheet alloc]  
                          initWithTitle:[NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"dateFin", @"")] 
                          delegate:self cancelButtonTitle:NSLocalizedString(@"Commun.button.cancel", @"") destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Commun.button.select", @""), nil]; 
    [actionSheetDateFin showInView:self.view]; 
    datePickerDateFin = [[UIDatePicker alloc] init]; 
    datePickerDateFin.datePickerMode = UIDatePickerModeDateAndTime; 
    [actionSheetDateFin addSubview:datePickerDateFin]; 
    
    if ([custody endDate] != nil){
        datePickerDateFin.date = [custody endDate];
    }else{
        datePickerDateFin.date=[NSDate date];
    }    
    
}

- (IBAction)processRetour {
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)processSave {
    
    [custody setName:[nameTextField text]];
    NSString *error = [custody validate];
    if (error != nil && error.length > 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ErrorPopupTitle", @"")
                                                        message:error
                                                       delegate:nil
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];

    }else{
        NSMutableArray *listCutodies = [messageUtils getArray:@"listCustodies"];
        int index = 0;
        if (!isNew){
            for(int i = 0; i < [listCutodies count]; i++)  {
                Custody *aCustody = [listCutodies objectAtIndex:i];
                if ([[aCustody uniqueId]isEqualToString:[custody uniqueId]]){
                    index = i;
                }
            }
            [listCutodies removeObjectAtIndex:index];
        }
        [listCutodies addObject:custody];
        [messageUtils setArrayForLabel:@"listCustodies" value:listCutodies];
        isNew = NO;
        [self updateParameters];
        [self dismissModalViewControllerAnimated:YES];
    }
    
}

- (void)updateParameters{
    if (!isNew){
        self.deleteButton.hidden = NO; 
    }else{
         self.deleteButton.hidden = YES; 
    }
}

- (IBAction)processDelete {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:NSLocalizedString(@"Custody.delete.confirm", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"Commun.button.cancel", @"") otherButtonTitles:NSLocalizedString(@"Commun.button.ok", @""), nil];
    [alert show];
 
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 1)
    {
        NSMutableArray *listCutodies = [messageUtils getArray:@"listCustodies"];
        int index = 0;
        for(int i = 0; i < [listCutodies count]; i++)  {
            Custody *aCustody = [listCutodies objectAtIndex:i];
            if ([[aCustody uniqueId]isEqualToString:[custody uniqueId]]){
                index = i;
            }
        }
        [listCutodies removeObjectAtIndex:index];
        [messageUtils setArrayForLabel:@"listCustodies" value:listCutodies];
        [self dismissModalViewControllerAnimated:YES];

    }
    
}



@end
